import 'dart:io';
import 'package:flutter/services.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

class DatabaseHelper {
  static Database? _db;
  static bool _initialized = false;

  /// 初始化数据库
  static Future<void> init() async {
    if (_initialized) {
      print('Database already initialized');
      return;
    }

    try {
      final dbPath = await getDatabasesPath();
      final path = join(dbPath, './db/code_study.db');
      
      print('Checking database file...');
      bool exists = await databaseExists(path);

// !exists 这里强制复制，因为开发阶段我需要填充词库
      if (true) {
        print('Copying database file...');
        try {
          await Directory(dirname(path)).create(recursive: true);
          ByteData data = await rootBundle.load('assets/db/code_study.db');
          List<int> bytes = data.buffer.asUint8List();
          await File(path).writeAsBytes(bytes, flush: true);
          print('Database file copied');
        } catch (e) {
          print('Failed to copy database: $e');
          return;
        }
      }

      print('Opening database...');
      _db = await openDatabase(path);
      _initialized = true;
      print('Database initialization completed');
    } catch (e) {
      print('Initialization failed: $e');
      rethrow;
    }
  }

  /// 获取数据库实例
  static Future<Database> get database async {
    if (_db == null) {
      await init();
    }
    return _db!;
  }

  /// 查询文章列表
  static Future<List<Map<String, dynamic>>> getArticles({int? difficulty}) async {
    if (_db == null) {
      print('Database not initialized');
      return [];
    }

    try {
      return await _db!.rawQuery('''
        SELECT id, title, source, difficulty, category, created_at 
        FROM articles
        ${difficulty != null ? 'WHERE difficulty = ?' : ''}
      ''', difficulty != null ? [difficulty] : []);
    } catch (e) {
      print('Query failed: $e');
      return [];
    }
  }

  /// 根据ID获取文章详情
  static Future<List<Map<String, dynamic>>> getArticleById(int articleId) async {
    if (_db == null) {
      print('Database not initialized');
      return [];
    }

    try {
      return await _db!.rawQuery('''
        SELECT id, title, source, difficulty, category, created_at, content
        FROM articles
        WHERE id = ?
      ''', [articleId]);
    } catch (e) {
      print('Query failed: $e');
      return [];
    }
  }

  /// 关闭数据库
  static Future<void> close() async {
    await _db?.close();
    _db = null;
    _initialized = false;
  }
}
